<template>
  <div>
    <el-dialog
      v-model="_dialogVisible"
      :title="`${admin_id ? '修改' : '添加'}管理员`"
      :before-close="handleClose"
      destroy-on-close
      draggable
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item v-if="!props.admin_id" label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="所属部门" prop="dept_id">
          <el-tree-select
            v-model="formData.dept_id"
            :data="deptTreeData"
            :props="{ label: 'dept_name', value: 'dept_id' }"
            check-strictly
            placeholder="请选择部门"
            default-expand-all
          />
        </el-form-item>
        <el-form-item label="所属岗位" prop="post_id">
          <el-select v-model="formData.post_id" placeholder="请选择岗位">
            <el-option
              v-for="item in postData"
              :key="item.post_id"
              :label="item.post_name"
              :value="item.post_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属角色" prop="role_id">
          <el-select v-model="formData.role_id" placeholder="请选择角色">
            <el-option
              v-for="item in roleData"
              :key="item.role_id"
              :label="item.role_name"
              :value="item.role_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="个人简介" prop="note">
          <el-input
            type="textarea"
            v-model="formData.note"
            placeholder="个人简介"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio-button :label="1">启用</el-radio-button>
            <el-radio-button :label="2">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handleSubmit">
          {{ admin_id ? '修改' : '添加' }}
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { AdminParams } from '@/api/auth/model/adminModel'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { useForm } from '@/hooks'
import { show, store, update } from '@/api/auth/admin'
import { VoListItem } from '@/api/auth/model/deptModel'
import { VoListResult } from '@/api/auth/model/postModel'
import { RoleVoList } from '@/api/auth/model/roleModel'
import { GetPostVoList } from '@/api/auth/post'
import { getDeptVoList } from '@/api/auth/dept'
import { getVolist } from '@/api/auth/role'
import handleTree from '@/utils/tree'

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  admin_id: {
    type: Number,
    default: 0,
  },
})

const { validate, resetForm } = useForm()
const emit = defineEmits(['update:dialogVisible', 'success'])
const formRef = ref<FormInstance>(null!)

const _dialogVisible = ref<boolean>(false)

let formData = ref<AdminParams | any>({
  admin_id: 0,
  dept_id: 0,
  email: '',
  nickname: '',
  note: '',
  phone: '',
  post_id: 0,
  role_id: 0,
  status: 1,
  username: '',
  password: '',
})

const deptTreeData = ref<VoListItem[]>([])
const postData = ref<VoListResult[]>([])
const roleData = ref<RoleVoList[]>([])

watch(
  () => props.dialogVisible,
  () => {
    props.dialogVisible && (getDeptTreeData(), getPostData(), getRoleData())
    _dialogVisible.value = props.dialogVisible
  }
)

watch(
  () => _dialogVisible.value,
  () => {
    emit('update:dialogVisible', _dialogVisible.value)
  }
)

const getDeptTreeData = async () => {
  const { code, message, data } = await getDeptVoList()
  if (code != 200) {
    ElMessage.error(message)
    return
  }
  formData.value.dept_id = data && data.length > 0 ? data[0].dept_id : 0
  deptTreeData.value = handleTree.handleTree(
    data,
    'dept_id',
    'parent_id',
    'children'
  )
}

const getPostData = async () => {
  const { code, message, data } = await GetPostVoList()
  if (code != 200) {
    ElMessage.error(message)
    return
  }
  formData.value.post_id = data && data.length > 0 ? data[0].post_id : 0
  postData.value = data as VoListResult[]
}

const getRoleData = async () => {
  const { code, message, data } = await getVolist()
  if (code != 200) {
    ElMessage.error(message)
    return
  }
  formData.value.role_id = data && data.length > 0 ? data[0].role_id : 0
  roleData.value = data as RoleVoList[]
}

//获取数据
const detail = async () => {
  if (props.admin_id) {
    const { code, message, data } = await show({ admin_id: props.admin_id })
    if (code != 200) {
      ElMessage.error(message)
      return
    }
    formData.value = data
  }
}

watch(
  () => [props.admin_id, props.dialogVisible],
  () => {
    props.dialogVisible && props.admin_id && detail()
  }
)

const handleClose = () => {
  resetForm(formRef.value)
  _dialogVisible.value = false
}

//验证用户名
const validateUserName = (rule: any, value: any, callback: any) => {
  console.log(rule, value, callback)

  if (!new RegExp('^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$').test(value)) {
    rule.message = '用户名不能有特殊字符'
    callback(new Error(rule.message))
  }
  if (/^\d+\d+\d$/.test(value)) {
    rule.message = '用户名不能全为数字'
    callback(new Error(rule.message))
  }
  callback()
}

//验证密码
const validatePassword = (rule: any, value: any, callback: any) => {
  const pwdRegex = new RegExp(
    '(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{6,18}'
  )
  if (!pwdRegex.test(value)) {
    /* eslint-disable-next-line */
    rule.message = '密码中必须包含大小写字母、数字、特殊字符,长度6到18位'
    callback(new Error(rule.message))
  }
  callback()
}

const rules = computed<FormRules<AdminParams>>(() => ({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
    {
      min: 5,
      max: 16,
      message: '用户名长度在5-16个字符',
      trigger: 'blur',
    },
    {
      validator: validateUserName,
      message: '用户名仅字母、数字和下划线组成的5-16位字符',
      trigger: 'blur',
    },
  ],
  nickname: {
    required: true,
    message: '请输入昵称',
    trigger: 'blur',
  },
  password: [
    {
      required: props.admin_id ? false : true,
      message: '请输入密码',
      trigger: 'blur',
    },
    {
      validator: validatePassword,
      message: '密码中必须包含大小写字母、数字、特殊字符,长度6到18位',
      trigger: 'blur',
    },
  ],
  email: {
    required: true,
    message: '请输入邮箱',
    trigger: 'blur',
  },
  phone: {
    required: true,
    message: '请输入手机号',
    trigger: 'blur',
  },
  deptId: {
    required: true,
    message: '请选择部门',
    trigger: 'blur',
  },
  postId: {
    required: true,
    message: '请选择岗位',
    trigger: 'blur',
  },
  roleId: {
    required: true,
    message: '请选择角色',
    trigger: 'blur',
  },
  status: {
    required: true,
    message: '请选择状态',
    trigger: 'blur',
  },
}))

const handleSubmit = async () => {
  await validate(formRef.value)

  //发送请求
  let result
  if (!props.admin_id) {
    result = await store(formData.value)
  } else {
    result = await update(formData.value)
  }
  const { code, message } = result
  if (code != 200) {
    ElMessage.error(`${props.admin_id ? '修改' : '添加'}${message}`)
    return
  }
  handleClose()
  ElMessage.success(`${props.admin_id ? '修改' : '添加'}${message}`)
  emit('success')
}
</script>

<style scoped></style>
